package com.jiantong.web.open.app.insurance;

import com.google.common.base.Throwables;
import com.jiantong.common.util.PingYinUtil;
import com.jiantong.common.util.UserUtil;
import com.jiantong.user.dto.BreedFactoryDto;
import com.jiantong.user.ext.LoginUser;
import com.jiantong.user.model.BreedFactory;
import com.jiantong.user.model.OrganizationUser;
import com.jiantong.user.model.User;
import com.jiantong.user.model.UserProfile;
import com.jiantong.user.service.BreedFactoryReadService;
import com.jiantong.user.service.OrganizationUserReadService;
import com.jiantong.user.service.UserProfileReadService;
import com.jiantong.user.service.UserReadService;
import com.jiantong.work.dto.*;
import com.jiantong.work.impl.manager.InsuranceApplicationManager;
import com.jiantong.work.model.yangzhibaoxian.*;
import com.jiantong.work.service.yangzhibaoxian.*;
import io.terminus.boot.rpc.common.annotation.RpcConsumer;
import io.terminus.common.model.PageInfo;
import io.terminus.common.model.Paging;
import io.terminus.pampas.openplatform.annotations.OpenBean;
import io.terminus.pampas.openplatform.annotations.OpenMethod;
import io.terminus.pampas.openplatform.exceptions.OPClientException;
import io.terminus.pampas.openplatform.exceptions.OPServerException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.sound.sampled.Line;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by ThinkPad on 2017/9/8.
 */
@OpenBean
@Slf4j
public class insuranceApplicationApis {

    @RpcConsumer
    private InsuranceApplicationService insuranceApplicationService;
    @RpcConsumer
    private UserProfileReadService userProfileReadService;
    @RpcConsumer
    private InsuranceAreaService insuranceAreaService;
    @RpcConsumer
    private InsuranceTemplateService insuranceTemplateService;
    @RpcConsumer
    private InsuranceApplicationManager insuranceApplicationManager;
    @RpcConsumer
    private BreedFactoryReadService breedFactoryReadService;
    @RpcConsumer
    private ProspectRecordService prospectRecordService;
    @RpcConsumer
    private InsuranceRetailService insuranceRetailService;
    @RpcConsumer
    private UserReadService userReadService;
    @RpcConsumer
    private FileService fileService;
    @RpcConsumer
    private InsuranceCheckService insuranceCheckService;
    @RpcConsumer
    private ClaimsSettlementService claimsSettlementService;
    @RpcConsumer
    private CustomerVisitService customerVisitService;
    @RpcConsumer
    private InformService informService;
    @RpcConsumer
    private OrganizationUserReadService organizationUserReadService;

    /**
     * 养殖投保
     *
     * @param insuranceApplication
     * @return
     */
    @OpenMethod(
            key = "insurance.create.InsuranceApplication1",
            paramNames = {"insuranceApplication"},
            httpMethods = RequestMethod.POST
    )

    public Long createApplication(InsuranceApplication insuranceApplication) {

        UserProfile userProfile = userProfileReadService.findUserProfileById(insuranceApplication.getApplication_org_id()).getResult();
        //市
        String cityID = userProfile.getCityId().toString();
        if (cityID.length() == 1) {
            cityID = "0" + cityID;
        }
        //县
        String regionID = userProfile.getRegionId().toString();
        if (regionID.length() == 1) {
            regionID = "0" + regionID;
        }
        // 镇
        String streetId = userProfile.getStreetId().toString();
        if (streetId.length() == 1) {
            streetId = "00" + streetId;
        }
        if (streetId.length() == 2) {
            streetId = "0" + streetId;
        }
        //村
        String villageId = null;
        if (userProfile.getStreetId() != null) {
            villageId = userProfile.getStreetId().toString();
        } else {
            villageId = "000";
        }
        if (villageId.length() == 1) {
            villageId = "00" + villageId;
        }
        if (villageId.length() == 2) {
            villageId = "0" + villageId;
        }
        String area = userProfile.getProvinceId().toString()
                + cityID
                + regionID
                + streetId
                + villageId;

        InsuranceArea insuranceArea = insuranceAreaService.findByAreaCode(area);
        Long receiver_id = -1L;
        String receiver_name = null;
        if (insuranceArea != null) {
            receiver_id = insuranceArea.getUser_id();
            receiver_name = insuranceArea.getUser_name();
        }


        insuranceApplication.setArea(area);
        insuranceApplication.setReceiver_id(receiver_id);
        insuranceApplication.setReceiver_name(receiver_name);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmm");
        String number = sdf.format(new Date());
        insuranceApplication.setInsured_number("InA" + number);
        insuranceApplication.setCheck_status(0);
        return insuranceApplicationService.create(insuranceApplication);

    }

    /**
     *客户访问
     */
    @OpenMethod(
            key = "insurance.create.customerVisit",
            paramNames = {"customerVisit"},
            httpMethods = RequestMethod.POST
    )
    public Long createCustomerVisit(CustomerVisit customerVisit){
        Long result = customerVisitService.create(customerVisit);
        if(result == -500L){
            throw new OPClientException("创建失败!失败请重试");
        }
        return result;
    }

    /**
     * 根据当前用户ID,name查询拜访记录分页列表
     */
    @OpenMethod(
            key = "insurance.create.customerVisitByCIdList",
            paramNames = {"create_id","name","pageNo","size"},
            httpMethods = RequestMethod.POST
    )
    public Paging<CustomerVisit> customerVisitByCIdList(Long create_id,String name,Integer pageNo,Integer size){
        List<CustomerVisit> customerVisitList = new ArrayList<>();
        Map map = new HashMap();
        if (create_id != null){
            map.put("create_id",create_id);
        }
        if (name != null)
            map.put("name","%" + name + "%");
        if (pageNo == null)
            pageNo = 1;
        if (size == null)
            size = 2;
        Paging<CustomerVisit> customerVisitPaging= customerVisitService.ping(pageNo,size,map).getResult();
        return customerVisitPaging;
    }

    /**
     * 根据拜访记录ID查询单据详情
     */
    @OpenMethod(
            key = "insurance.create.customerVisitById",
            paramNames = {"id"},
            httpMethods = RequestMethod.POST
    )
    public CustomerVisit customerVisitById(Long id){
        if (id == null){
            throw new OPClientException("id不能为空!");
        }
        return customerVisitService.findById(id).getResult();
    }

    /**
     * 根据通知ID查询通知详情
     */
    @OpenMethod(
            key = "select.inform.informById",
            paramNames = {"id","userId"},
            httpMethods = RequestMethod.POST
    )
    public Inform informById(Long id,Long userId){
        Map map = new HashMap();
        if (id !=null){
            map.put("id",id);
            if (userId != null)
                map.put("get_message_id",userId);
        }else
            throw new OPClientException("查阅出错,缺少id,请重新查阅");

        //根据消息通知id查询到的结果为长度为1或者0的数组
        List<Inform> informList = informService.list(map).getResult();
        Inform inform = null;
        if (informList != null){
            inform =  informList.get(0);
            if (inform.getStatus() == 0){
                inform.setStatus(1);
                //更新消息通知查看的状态
                informService.update(inform);
            }
        }
        return inform;
    }

    /**
     * 根据当前用户ID得到所属公司所有员工列表
     */
    @OpenMethod(
            key = "select.organizationUsers.userListByUserId",
            paramNames = {"userId"},
            httpMethods = RequestMethod.POST
    )
    public List<OrganizationUserDto> userListByUserId(Long userId){
        List<OrganizationUserDto> organizationUserDtoList = new ArrayList<>();

        OrganizationUser organizationUser = null;
        Map map = new HashMap();
        if (userId != null)
            //组织人员信息表中根据用户id查询到对应的数据
            organizationUser = organizationUserReadService.findOrganizationUserByUserId(userId).getResult();
        if (organizationUser != null)
            map.put("organizationId",organizationUser.getOrganizationId());
        //根据查询到的组织id查找到该组织下所有人员列表
        List<OrganizationUser> organizationUserList = organizationUserReadService.selectList(map).getResult();

        OrganizationUserDto organizationUserDto = new OrganizationUserDto();
        //循环录入对应信息到Dto中
        for(OrganizationUser o : organizationUserList){
            organizationUserDto.setUserId(o.getUserId());
            organizationUserDto.setName(o.getUserName());
            organizationUserDto.setGroupIndex(PingYinUtil.getPinYinHeadChar(o.getUserName()));

            User user = (User)userReadService.findUserByUserId(o.getUserId()).getResult();
            organizationUserDto.setPhone(user.getMobile());

            Map map1 = new HashMap();
            map1.put("user_id",o.getUserId());
            //根据user_id到区域管理表中查询出此id管辖的区域列表
            List<InsuranceArea> insuranceAreaList = insuranceAreaService.list(map1).getResult();

            List<String> precinct = new ArrayList<>();
            for(InsuranceArea insuranceArea : insuranceAreaList){
                StringBuffer str = new StringBuffer();
                if (insuranceArea.getProvince() != null)
                    str.append(insuranceArea.getProvince());
                if (insuranceArea.getCity() != null)
                    str.append(insuranceArea.getCity());
                if (insuranceArea.getRegion() != null)
                    str.append(insuranceArea.getRegion());
                if (insuranceArea.getStreet() != null)
                    str.append(insuranceArea.getStreet());
                if (insuranceArea.getVillage() != null)
                    str.append(insuranceArea.getVillage());
                if (str != null)
                    precinct.add(str.toString());
            }
            organizationUserDto.setPrecinctList(precinct);
            organizationUserDtoList.add(organizationUserDto);
        }
        return organizationUserDtoList;
    }

    /**
     * 根据当前用户ID,查阅状态 得到所属公司发表的通知列表
     */
    @OpenMethod(
            key = "select.inform.informListByUserId",
            paramNames = {"userId","status","pageNo","size"},
            httpMethods = RequestMethod.POST
    )
    public Paging<Inform> informListByUserId(Long userId,Integer status, Integer pageNo, Integer size){
        OrganizationUser organizationUser = null;
        Map map = new HashMap();
        //根据当前用户id查询其所属公司的所有员工信息
        if (userId == null)
            throw new OPClientException("查询出错,用户id为空");
        organizationUser = organizationUserReadService.findOrganizationUserByUserId(userId).getResult();
        if (organizationUser != null)
            map.put("organizationId",organizationUser.getOrganizationId());
        List<OrganizationUser> organizationUserList = organizationUserReadService.selectList(map).getResult();

        Map map1 = new HashMap();
        //遍历该公司所有员工,方便查询该公司员工发布的所有通知
        for(OrganizationUser o : organizationUserList)
            map1.put("userIdList",o.getUserId());

        //根据当前用户查阅该用户对的应消息通知
        if (userId != null){
            map1.put("get_message_id",userId);
            if (status != null)
                map1.put("status",status);
        }else
            throw new OPClientException("查询出错,缺少用户id,请重新查阅");

        return informService.ping(pageNo,size,map).getResult();
    }

    /**
     * 散户投保
     *
     * @param insuranceApplication
     * @param insuranceRetailList
     * @return
     */
    @OpenMethod(
            key = "insurance.create.InsuranceApplication2",
            paramNames = {"insuranceApplication", "insuranceRetailList"},
            httpMethods = RequestMethod.POST
    )

    public Long createApplication(InsuranceApplication insuranceApplication, List<Map<String, Object>> insuranceRetailList) {

        UserProfile userProfile = userProfileReadService.findUserProfileById(insuranceApplication.getApplication_org_id()).getResult();
        //市
        String cityID = userProfile.getCityId().toString();
        if (cityID.length() == 1) {
            cityID = "0" + cityID;
        }
        //县
        String regionID = userProfile.getRegionId().toString();
        if (regionID.length() == 1) {
            regionID = "0" + regionID;
        }
        // 镇
        String streetId = userProfile.getStreetId().toString();
        if (streetId.length() == 1) {
            streetId = "00" + streetId;
        }
        if (streetId.length() == 2) {
            streetId = "0" + streetId;
        }
        //村
        String villageId = null;
        if (userProfile.getStreetId() != null) {
            villageId = userProfile.getStreetId().toString();
        } else {
            villageId = "000";
        }
        if (villageId.length() == 1) {
            villageId = "00" + villageId;
        }
        if (villageId.length() == 2) {
            villageId = "0" + villageId;
        }
        String area = userProfile.getProvinceId().toString()
                + cityID
                + regionID
                + streetId
                + villageId;


        InsuranceArea insuranceArea = insuranceAreaService.findByAreaCode(area);

        Long receiver_id = -1L;
        String receiver_name = null;
        if (insuranceArea != null) {
            receiver_id = insuranceArea.getUser_id();
            receiver_name = insuranceArea.getUser_name();
        }

        insuranceApplication.setArea(area);
        insuranceApplication.setReceiver_id(receiver_id);
        insuranceApplication.setReceiver_name(receiver_name);
        SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMddhhmm");
        String number = sdf.format(new Date());
        insuranceApplication.setInsured_number("InA" + number);
        insuranceApplication.setCheck_status(0);
        List<InsuranceRetail> insuranceRetailList1 = new ArrayList<>();
        for (Map map : insuranceRetailList) {
            InsuranceRetail insuranceRetail = new InsuranceRetail();
            insuranceRetail.setInsured_count((int) map.get("insured_count"));
            Integer breed_factory_id = (int) map.get("breed_factory_id");
            insuranceRetail.setBreed_factory_id(breed_factory_id.longValue());
            insuranceRetail.setBreed_factory_id_name((String) map.get("breed_factory_id_name"));
            insuranceRetailList1.add(insuranceRetail);
        }
        return insuranceApplicationManager.create(insuranceApplication, insuranceRetailList1);
    }

    /**
     * 投保模板
     *
     * @return
     */
    @OpenMethod(
            key = "select.insurance.InsuranceTemplate",
            httpMethods = RequestMethod.POST
    )
    public List<InsuranceTemplate> selectInsuranceTemplate() {

        List<InsuranceTemplate> insuranceTemplateList = insuranceTemplateService.list(new HashMap()).getResult();


        return insuranceTemplateList;
    }

    /**
     * 根据id查询投保单
     *
     * @param id
     * @return
     */
    @OpenMethod(
            key = "select.insurance.InsuranceApplicationByID",
            paramNames = {"id"},
            httpMethods = RequestMethod.POST
    )
    public InsuranceApplication InsuranceApplicationByID(Long id) {
        return insuranceApplicationService.findById(id).getResult();
    }

    /**
     * 根据单号查询投保单
     *
     * @param formal_number
     * @return
     */
    @OpenMethod(
            key = "select.insurance.InsuranceApplicationByNumber",
            paramNames = {"formal_number"},
            httpMethods = RequestMethod.POST
    )
    public InsuranceApplication insuranceApplicationByNumber(String formal_number) {
        return insuranceApplicationService.findBynumber(formal_number).getResult();
    }

    /**
     * 政府端根据投保 id查询散户投保列表
     *
     * @param id
     * @return
     */
    @OpenMethod(
            key = "select.insurance.InsuranceRetailDtoByID",
            paramNames = {"id"},
            httpMethods = RequestMethod.POST
    )
    public InsuranceRetailDto InsuranceRetailDtoByID(Long id) {
        InsuranceRetailDto insuranceRetailDto = new InsuranceRetailDto();
        InsuranceApplication insuranceApplication = insuranceApplicationService.findById(id).getResult();
        Map map1 = new HashMap();
        map1.put("application_id", insuranceApplication.getId());
        List<InsuranceRetail> insuranceRetailList = insuranceRetailService.list(map1).getResult();
        map1.put("relevance_id", insuranceApplication.getId());
        List<Integer> integerList = new ArrayList<>();
        map1.put("type1", 4);
        List<File> fileList = fileService.list(map1).getResult();
        Map mapPro = new HashMap();
        mapPro.put("insurance_application_id", insuranceApplication.getId());

        List<ProspectRecord> prospectRecords = prospectRecordService.list(mapPro).getResult();
        if (prospectRecords.size() != 0) {
            mapPro.put("type1", 1);
            mapPro.put("relevance_id", prospectRecords.get(0).getId());
        } else {
            mapPro.put("type1", -1);

        }
        List<File> fileList1 = fileService.list(mapPro).getResult();
        fileList.addAll(fileList1);
        InsuranceCheck insuranceCheck = insuranceCheckService.findByApplicationId(insuranceApplication.getId());

        insuranceRetailDto.setFiles(fileList);
        insuranceRetailDto.setInsuranceCheck(insuranceCheck);
        insuranceRetailDto.setInsuranceRetailList(insuranceRetailList);
        insuranceRetailDto.setInsuranceApplication(insuranceApplication);

        return insuranceRetailDto;
    }


    /**
     * 政府端查看自己管辖范围内   散户投保情况
     *
     * @param check_status（list）
     * @param year
     * @return
     */
    @OpenMethod(
            key = "select.insurance.insuranceRetailDtoList1",
            paramNames = {"check_status", "year"},
            httpMethods = RequestMethod.POST
    )
    public List<GovApplication> insuranceRetailDtoList1(List check_status, int year) {

        List<GovApplication> govApplications = new ArrayList<>();
        //查询所有养殖场列表
        LoginUser loginUser = UserUtil.getCurrentUser();
        List<Long> longList = loginUser.getBreedFactoryIds();
        List<BreedFactory> breedFactoryList = breedFactoryReadService.findBreedFactoryDtoByIds(longList).getResult();
        List<BreedFactory> breedFactories = new ArrayList<>();
        for (BreedFactory breedFactory : breedFactoryList) {
            if ((breedFactory.getIsScale() == 0)) {
                breedFactories.add(breedFactory);
            }
        }
        //查出所有村
        List<String> stringList = new ArrayList<>();
        for (BreedFactory breedFactory : breedFactories) {
            stringList.add(breedFactory.getVillage());
        }

        List<String> stringList1 = new ArrayList<>(new HashSet<>(stringList));

        //遍历村
        for (String village : stringList1) {
            GovApplication govApplication = new GovApplication();
            //set村庄
            govApplication.setVillage(village);
            //得到该村的养殖场id列表
            List<Long> longList1 = new ArrayList<>();
            for (BreedFactory breedFactory : breedFactories) {
                if (breedFactory.getVillage().equals(village) && breedFactory.getIsScale() == 0) {
                    longList1.add(breedFactory.getId());
                }
            }

            //通散户投保表获得保单  list（id）集合
            Map map = new HashMap();
            map.put("breedIDList", longList1);
            List<InsuranceRetail> insuranceRetailList = insuranceRetailService.list(map).getResult();
            List<Long> breedIDList = new ArrayList<>();
            if (insuranceRetailList.size() != 0) {
                for (InsuranceRetail insuranceRetail : insuranceRetailList) {
                    breedIDList.add(insuranceRetail.getApplication_id());
                }
            }

            Map map1 = new HashMap();
            map1.put("Liststatus", check_status);
            map1.put("ids", breedIDList);
            map1.put("year", year);
            List<InsuranceApplication> insuranceApplicationList = insuranceApplicationService.list(map1).getResult();

            //set 保单
            govApplication.setInsuranceApplicationList(insuranceApplicationList);
            //得到该村投保养殖场列表
            List<Long> longList2 = new ArrayList<>();
            if (insuranceApplicationList.size() != 0) {
                for (InsuranceApplication insuranceApplication : insuranceApplicationList) {
                    longList2.add(insuranceApplication.getInsured_breed_id());
                }
            }

            //得到未投保养殖场list
            longList1.removeAll(longList2);
            List<BreedFactory> factoryList = breedFactoryReadService.findBreedFactoryDtoByIds(longList1).getResult();
            List<Long> userIDList = new ArrayList<>();
            if (factoryList.size() != 0) {
                for (BreedFactory breedFactory : factoryList) {
                    userIDList.add(breedFactory.getUserId());
                }
            }
            List<User> userList = (List<User>) userReadService.findByIds(userIDList).getResult();
            List<BreedFactoryDto> breedFactoryDtoList = new ArrayList<>();
            BreedFactory bf = new BreedFactory();
            User us = new User();
            try {
                if (!factoryList.isEmpty() && (factoryList.size() == userList.size())) {
                    for (int i = 0; i < factoryList.size(); i++) {
                        //拿到单个的BreedFactory和User 并判断id和user_id对应的一组组成一个BreedFactoryDto
                        bf = factoryList.get(i);
                        for (int j = 0; j < factoryList.size(); j++) {
                            us = userList.get(j);
                            if (us.getId().equals(bf.getUserId())) {
                                BreedFactoryDto bfd = new BreedFactoryDto();
                                bfd.setBreedFactory(bf);
                                bfd.setUser(us);
                                breedFactoryDtoList.add(i, bfd);
                                break;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.error("failed structure breedFactoryDtoList cause:{}", Throwables.getStackTraceAsString(e));
                throw new OPServerException("create breedFactoryDto failed");
            }

            govApplication.setBreedFactoryDtoList(breedFactoryDtoList);
            govApplications.add(govApplication);

        }

        return govApplications;

    }


    /**
     * 政府端查看自己管辖范围内    规模场投保情况
     *
     * @param check_status（list）
     * @param year
     * @return
     */
    @OpenMethod(
            key = "select.insurance.insuranceRetailDtoList",
            paramNames = {"check_status", "year"},
            httpMethods = RequestMethod.POST
    )
    public List<GovApplication> insuranceRetailDtoList(List check_status, int year) {

        List<GovApplication> govApplications = new ArrayList<>();
        //查询所有养殖场列表
        LoginUser loginUser = UserUtil.getCurrentUser();
        List<Long> longList = loginUser.getBreedFactoryIds();
        List<BreedFactory> breedFactoryList = breedFactoryReadService.findBreedFactoryDtoByIds(longList).getResult();
        List<BreedFactory> breedFactories = new ArrayList<>();
        for (BreedFactory breedFactory : breedFactoryList) {
            if ((breedFactory.getIsScale() == 1)) {
                breedFactories.add(breedFactory);
            }
        }
        //查出所有村
        List<String> stringList = new ArrayList<>();
        for (BreedFactory breedFactory : breedFactories) {
            stringList.add(breedFactory.getVillage());
        }

        List<String> stringList1 = new ArrayList<>(new HashSet<>(stringList));

        //遍历村
        for (String village : stringList1) {
            GovApplication govApplication = new GovApplication();
            //set村庄
            govApplication.setVillage(village);
            //得到该村的养殖场id列表
            List<Long> longList1 = new ArrayList<>();
            for (BreedFactory breedFactory : breedFactories) {
                if (breedFactory.getVillage().equals(village) && breedFactory.getIsScale() == 1) {
                    longList1.add(breedFactory.getId());
                }
            }

            Map map = new HashMap();
            map.put("Liststatus", check_status);
            map.put("breedIDList", longList1);
            map.put("year", year);
            List<InsuranceApplication> insuranceApplicationList = insuranceApplicationService.list(map).getResult();
            //set 保单
            govApplication.setInsuranceApplicationList(insuranceApplicationList);
            //得到该村投保养殖场列表
            List<Long> longList2 = new ArrayList<>();
            if (insuranceApplicationList.size() != 0) {
                for (InsuranceApplication insuranceApplication : insuranceApplicationList) {
                    longList2.add(insuranceApplication.getInsured_breed_id());
                }
            }

            //得到未投保养殖场list
            longList1.removeAll(longList2);
            List<BreedFactory> factoryList = breedFactoryReadService.findBreedFactoryDtoByIds(longList1).getResult();
            List<Long> userIDList = new ArrayList<>();
            if (factoryList.size() != 0) {
                for (BreedFactory breedFactory : factoryList) {
                    userIDList.add(breedFactory.getUserId());
                }
            }
            List<User> userList = (List<User>) userReadService.findByIds(userIDList).getResult();
            List<BreedFactoryDto> breedFactoryDtoList = new ArrayList<>();
            BreedFactory bf = new BreedFactory();
            User us = new User();
            try {
                if (!factoryList.isEmpty() && (factoryList.size() == userList.size())) {
                    for (int i = 0; i < factoryList.size(); i++) {
                        //拿到单个的BreedFactory和User 并判断id和user_id对应的一组组成一个BreedFactoryDto
                        bf = factoryList.get(i);
                        for (int j = 0; j < factoryList.size(); j++) {
                            us = userList.get(j);
                            if (us.getId().equals(bf.getUserId())) {
                                BreedFactoryDto bfd = new BreedFactoryDto();
                                bfd.setBreedFactory(bf);
                                bfd.setUser(us);
                                breedFactoryDtoList.add(i, bfd);
                                break;
                            }
                        }
                    }
                }
            } catch (Exception e) {
                log.error("failed structure breedFactoryDtoList cause:{}", Throwables.getStackTraceAsString(e));
                throw new OPServerException("create breedFactoryDto failed");
            }

            govApplication.setBreedFactoryDtoList(breedFactoryDtoList);
            govApplications.add(govApplication);

        }

        return govApplications;

    }

    /**
     * 散户列表
     *
     * @return
     */
    @OpenMethod(
            key = "select.insurance.breedFactoryList",
            //paramNames = {"breedType","provinceId","cityId","regionId","streetId","villageId" },
            // && (breedFactory.getProvinceId() == provinceId) && (breedFactory.getCityId() == cityId) && (breedFactory.getStreetId()==streetId) && (breedFactory.getVillageId() == villageId)&&(breedFactory.getBreedType()==breedType)&&(breedFactory.getRegionId()==regionId
            httpMethods = RequestMethod.POST
    )
    public List<BreedFactory> breedFactoryList() {
        LoginUser loginUser = UserUtil.getCurrentUser();
        List<BreedFactory> breedFactoryList = breedFactoryReadService.findBreedFactoryDtoByIds(loginUser.getBreedFactoryIds()).getResult();
        List<BreedFactory> breedFactories = new ArrayList<>();
        for (BreedFactory breedFactory : breedFactoryList) {
            if ((breedFactory.getIsScale() == 0)) {
                breedFactories.add(breedFactory);
            }
        }
        return breedFactories;
    }


    /**
     * 养殖端根据被投保人id查询当前时间内有没有投保?
     *
     * @param insured_breed_id
     * @return
     */
    @OpenMethod(
            key = "select.insurance.insuranceApplicationStatus",
            paramNames = {"insured_breed_id"},
            httpMethods = RequestMethod.POST
    )
    public List<InsuranceApplication> insuranceApplicationList(Long insured_breed_id) {

        Map map = new HashMap();
        map.put("insured_breed_id", insured_breed_id);
        map.put("check_status", 4);
        map.put("date", new Date());
        return insuranceApplicationService.list(map).getResult();
    }

    /**
     * 保险端  查询投保单据
     * check_status 0已提交1初审通过2初审未通过3已勘察4审核通过5审核不通过
     *
     * @param receiver_id 保险端受理人id
     * @return
     */
    @OpenMethod(
            key = "select.insurance.INAInsuranceApplicationList",
            paramNames = {"receiver_id", "check_status", "pageNo", "pageSize", "year"},
            httpMethods = RequestMethod.POST
    )
    public Paging<InsuranceRetailDto> govinsuranceApplicationList(Long receiver_id, List check_status, int pageNo, int pageSize, int year) {
        Map map = new HashMap();
        map.put("Liststatus", check_status);
        map.put("receiver_id", receiver_id);
        map.put("year", year);
        Paging<InsuranceApplication> insuranceApplicationList = insuranceApplicationService.ping(pageNo, pageSize, map).getResult();
        List<InsuranceRetailDto> retailDtoList = new ArrayList<>();
        if (insuranceApplicationList.getData().size() != 0) {
            for (InsuranceApplication insuranceApplication : insuranceApplicationList.getData()) {
                InsuranceRetailDto insuranceRetailDto = new InsuranceRetailDto();
                Map map1 = new HashMap();
                map1.put("application_id", insuranceApplication.getId());
                List<InsuranceRetail> insuranceRetailList = insuranceRetailService.list(map1).getResult();
                insuranceRetailDto.setInsuranceApplication(insuranceApplication);
                insuranceRetailDto.setInsuranceRetailList(insuranceRetailList);
                retailDtoList.add(insuranceRetailDto);

            }
        }

        return new Paging<InsuranceRetailDto>(insuranceApplicationList.getTotal(), retailDtoList);
    }

    /**
     * 养殖端 查询投保单据
     * check_status 0已提交1初审通过2初审未通过3已勘察4审核通过5审核不通过
     * insured_breed_id  养殖场id
     *
     * @param
     * @return
     */
    @OpenMethod(
            key = "select.insurance.breeInsuranceApplicationList",
            paramNames = {"check_status", "insured_breed_id"},
            httpMethods = RequestMethod.POST
    )
    public List<InsuranceApplication> breeInsuranceApplicationList(List check_status, Long insured_breed_id) {
        Map map = new HashMap();
        Calendar now = Calendar.getInstance();
        map.put("Liststatus", check_status);
        map.put("insured_breed_id", insured_breed_id);
        map.put("year", now.get(Calendar.YEAR));
        return insuranceApplicationService.list(map).getResult();
    }

    /**
     * 政府端 查询投保单据
     * check_status 0已提交1初审通过2初审未通过3已勘察4审核通过5审核不通过
     *
     * @param check_status(list) application_org_id(投保人id)
     * @return
     */
    @OpenMethod(
            key = "select.insurance.govInsuranceApplicationList",
            paramNames = {"application_org_id", "check_status", "pageNo", "pageSize"},
            httpMethods = RequestMethod.POST
    )
    public Paging<InsuranceRetailDto> insuranceRetailDtoList(Long application_org_id, List check_status, int pageNo, int pageSize) {
        Map map = new HashMap();
        Calendar now = Calendar.getInstance();
        map.put("Liststatus", check_status);
        map.put("application_org_id", application_org_id);
        map.put("year", now.get(Calendar.YEAR));
        Paging<InsuranceApplication> insuranceApplicationList = insuranceApplicationService.ping(pageNo, pageSize, map).getResult();
        List<InsuranceRetailDto> retailDtoList = new ArrayList<>();
        if (insuranceApplicationList.getData().size() != 0) {
            for (InsuranceApplication insuranceApplication : insuranceApplicationList.getData()) {
                InsuranceRetailDto insuranceRetailDto = new InsuranceRetailDto();
                Map map1 = new HashMap();
                map1.put("application_id", insuranceApplication.getId());
                List<InsuranceRetail> insuranceRetailList = insuranceRetailService.list(map1).getResult();
                insuranceRetailDto.setInsuranceApplication(insuranceApplication);
                insuranceRetailDto.setInsuranceRetailList(insuranceRetailList);
                retailDtoList.add(insuranceRetailDto);

            }
        }
        return new Paging<InsuranceRetailDto>(insuranceApplicationList.getTotal(), retailDtoList);
    }

    /**
     * 修改投保单据
     *
     * @param check_status
     * @param id
     * @return
     */

    @OpenMethod(
            key = "update.insurance.updateInsuranceApplication",
            paramNames = {"check_status", "id"},
            httpMethods = RequestMethod.POST
    )
    public Boolean updateInsuranceApplication(int check_status, Long id) {

        InsuranceApplication insuranceApplication = insuranceApplicationService.findById(id).getResult();
        insuranceApplication.setCheck_status(check_status);
        return insuranceApplicationService.update(insuranceApplication);
    }


    /**
     * 投保单或者理赔单 丑拒接口
     *
     * @param check_status
     * @param id
     * @return
     */
    @OpenMethod(
            key = "update.insurance.updateInsuranceApplicationFail",
            paramNames = {"check_status", "id", "insuranceCheck"},
            httpMethods = RequestMethod.POST
    )
    @Transactional
    public Boolean updateInsuranceApplicationFail(int check_status, Long id, InsuranceCheck insuranceCheck) {

        if (insuranceCheck.getCheck_type() == 1) {
            InsuranceApplication insuranceApplication = insuranceApplicationService.findById(id).getResult();
            insuranceApplication.setCheck_status(check_status);

            insuranceCheckService.create(insuranceCheck);
            return insuranceApplicationService.update(insuranceApplication);
        } else if (insuranceCheck.getCheck_type() == 2) {
            ClaimsSettlement claimsSettlement = claimsSettlementService.findById(id).getResult();
            claimsSettlement.setCheck_status(check_status);
            insuranceCheckService.create(insuranceCheck);
            return claimsSettlementService.update(claimsSettlement);
        } else {
            return false;
        }


    }

    /**
     * 养殖端 修改投保正式单号
     *
     * @param formal_number
     * @param id
     * @return
     */
    @OpenMethod(
            key = "update.insurance.updateInsuranceApplicationNumber",
            paramNames = {"formal_number", "id"},
            httpMethods = RequestMethod.POST
    )
    public Boolean updateInsuranceApplicationNumber(String formal_number, Long id) {

        InsuranceApplication insuranceApplication = insuranceApplicationService.findById(id).getResult();
        insuranceApplication.setFormal_number(formal_number);
        return insuranceApplicationService.update(insuranceApplication);
    }

    /**
     * 保险端 完成最终投保
     *
     * @param formal_number
     * @param id
     * @return
     */
    @OpenMethod(
            key = "update.insurance.updateInsuranceApplicationOver",
            paramNames = {"formal_number", "id", "file", "check_status"},
            httpMethods = RequestMethod.POST
    )
    public Boolean updateInsuranceApplicationNumber(String formal_number, Long id, File file, int check_status) {

        InsuranceApplication insuranceApplication = insuranceApplicationService.findById(id).getResult();
        insuranceApplication.setCheck_status(check_status);
        insuranceApplication.setFormal_number(formal_number);
        if (file != null) {
            fileService.create(file);
        }
        return insuranceApplicationService.update(insuranceApplication);
    }


    /**
     * 保险端  勘查流程保存
     *
     * @param insured_startdate
     * @param insured_enddate
     * @param insuranceCheck
     * @return
     */
    @OpenMethod(
            key = "update.insurance.updateInsuranceApplication1",
            paramNames = {"insured_startdate", "insured_enddate", "insuranceCheck"},
            httpMethods = RequestMethod.POST
    )

    @Transactional
    public Boolean updateInsuranceApplication1(Date insured_startdate, Date insured_enddate, InsuranceCheck insuranceCheck) {

        InsuranceApplication insuranceApplication = insuranceApplicationService.findById(insuranceCheck.getApplication_id()).getResult();

        insuranceApplication.setInsured_startdate(insured_startdate);
        insuranceApplication.setInsured_enddate(insured_enddate);

        insuranceCheckService.create(insuranceCheck);
        Boolean b = insuranceApplicationService.update(insuranceApplication);

        return b;
    }

    /**
     * 创建投保勘察
     *
     * @param prospectRecord
     * @return
     */
    @OpenMethod(
            key = "create.insurance.prospectRecord",
            paramNames = {"prospectRecord"},
            httpMethods = RequestMethod.POST
    )
    public Long createProspectRecord(ProspectRecord prospectRecord) {

        InsuranceApplication insuranceApplication = insuranceApplicationService.findById(prospectRecord.getInsurance_application_id()).getResult();
        insuranceApplication.setCheck_status(3);
        insuranceApplicationService.update(insuranceApplication);
        return prospectRecordService.create(prospectRecord);
    }

    /**
     * 首页展示代办事项
     *
     * @param receiver_id
     * @return
     */
    @OpenMethod(
            key = "select.insurance.insuranceClaimsDto",
            paramNames = {"receiver_id"},
            httpMethods = RequestMethod.POST
    )
    public InsuranceClaimsDto insuranceClaimsDto(Long receiver_id) {

        InsuranceClaimsDto insuranceClaimsDto = new InsuranceClaimsDto();
        Map map = new HashMap();
        map.put("receiver_id", receiver_id);
        map.put("check_status", 0);
        List<InsuranceApplication> insuranceApplicationList = insuranceApplicationService.list(map).getResult();
        List<ClaimsSettlement> claimsSettlementList = claimsSettlementService.list(map).getResult();
        if (insuranceApplicationList.size() <= 10) {
            insuranceClaimsDto.setInsuranceApplicationList(insuranceApplicationList);
        } else {
            insuranceClaimsDto.setInsuranceApplicationList(insuranceApplicationList.subList(0, 9));

        }
        if (claimsSettlementList.size() <= 10) {
            insuranceClaimsDto.setClaimsSettlementList(claimsSettlementList);
        } else {
            insuranceClaimsDto.setClaimsSettlementList(claimsSettlementList.subList(0, 9));
        }

        return insuranceClaimsDto;
    }

}
